﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using t01crm.Data;
using System.Collections.ObjectModel;
using System.Windows;

namespace t01crm.View
{
    public class CatalogMaintainViewModel : ViewModelBase
    {
         #region Data
         ObservableCollection<CatalogViewModel> _firstGeneration;
         //ReadOnlyCollection<CatalogViewModel> 
         CatalogViewModel _rootCatalogViewModel;
        //readonly ICommand _searchCommand;

        //IEnumerator<CatalogViewModel> _matchingPeopleEnumerator;
        //string _searchText = String.Empty;

        #endregion // Data

        #region Constructor

          

        public CatalogMaintainViewModel()
        {
            RunInitTree();
        }

        private void RunInitTree()
        {
            HG_Prod_Catalog rootcatalog = CatalogMaintainViewModel.GetTree();
            _rootCatalogViewModel = new CatalogViewModel(rootcatalog);

            //_firstGeneration = new ReadOnlyCollection<CatalogViewModel>(
            //    new CatalogViewModel[] 
            //    { 
            //        _rootCatalogViewModel 
            //    });
            _firstGeneration = _rootCatalogViewModel.Children;
            // _searchCommand = new SearchFamilyTreeCommand(this);
        }

        #endregion // Constructor

        #region Properties

        #region FirstGeneration

        /// <summary>
        /// Returns a read-only collection containing the first person 
        /// in the family tree, to which the TreeView can bind.
        /// </summary>
        public ObservableCollection<CatalogViewModel> FirstGeneration
        {
            get
            {
                return _firstGeneration;
            }
            set
            {
                if (_firstGeneration != value)
                {
                    _firstGeneration = value;
                    FirePropertyChanged("FirstGeneration");
                }
            }
        }
        //private CatalogViewModel currentCatalog;
        //public CatalogViewModel CurrentCatalog
        //{
        //    get {
        //        return _firstGeneration.Where(c => c.IsSelected).FirstOrDefault();
        //    }
        //    set
        //    {
        //        if (value != currentCatalog)
        //        {
        //            currentCatalog = value;
        //            _firstGeneration.Where(c => c.Name==currentCatalog.Name).FirstOrDefault();
        //            FirePropertyChanged("CurrentCatalog");
        //        }
        //    }
        //}
        #endregion // FirstGeneration

        #region SearchCommand

        /// <summary>
        /// Returns the command used to execute a search in the family tree.
        /// </summary>
        //public ICommand SearchCommand
        //{
        //    get { return _searchCommand; }
        //}

        //private class SearchFamilyTreeCommand : ICommand
        //{
        //    readonly FamilyTreeViewModel _familyTree;

        //    public SearchFamilyTreeCommand(FamilyTreeViewModel familyTree)
        //    {
        //        _familyTree = familyTree;
        //    }

        //    public bool CanExecute(object parameter)
        //    {
        //        return true;
        //    }

        //    event EventHandler ICommand.CanExecuteChanged
        //    {
        //        // I intentionally left these empty because
        //        // this command never raises the event, and
        //        // not using the WeakEvent pattern here can
        //        // cause memory leaks.  WeakEvent pattern is
        //        // not simple to implement, so why bother.
        //        add { }
        //        remove { }
        //    }

        //    public void Execute(object parameter)
        //    {
        //        _familyTree.PerformSearch();
        //    }
        //}

        #endregion // SearchCommand

        #region SearchText

        /// <summary>
        /// Gets/sets a fragment of the name to search for.
        /// </summary>
        //public string SearchText
        //{
        //    get { return _searchText; }
        //    set
        //    {
        //        if (value == _searchText)
        //            return;

        //        _searchText = value;

        //        _matchingPeopleEnumerator = null;
        //    }
        //}

        #endregion // SearchText

        #endregion // Properties

        #region Search Logic

        //void PerformSearch()
        //{
        //    if (_matchingPeopleEnumerator == null || !_matchingPeopleEnumerator.MoveNext())
        //        this.VerifyMatchingPeopleEnumerator();

        //    var person = _matchingPeopleEnumerator.Current;

        //    if (person == null)
        //        return;

        //    // Ensure that this person is in view.
        //    if (person.Parent != null)
        //        person.Parent.IsExpanded = true;

        //    person.IsSelected = true;
        //}

        //void VerifyMatchingPeopleEnumerator()
        //{
        //    var matches = this.FindMatches(_searchText, _rootCatalog);
        //    _matchingPeopleEnumerator = matches.GetEnumerator();

        //    if (!_matchingPeopleEnumerator.MoveNext())
        //    {
        //        MessageBox.Show(
        //            "No matching names were found.",
        //            "Try Again",
        //            MessageBoxButton.OK,
        //            MessageBoxImage.Information
        //            );
        //    }
        //}

        //IEnumerable<CatalogViewModel> FindMatches(string searchText, CatalogViewModel person)
        //{
        //    if (person.NameContainsText(searchText))
        //        yield return person;

        //    foreach (CatalogViewModel child in person.Children)
        //        foreach (CatalogViewModel match in this.FindMatches(searchText, child))
        //            yield return match;
        //}

        #endregion // Search Logic

        public static HG_Prod_Catalog GetTree()
        {
            using (tb01crmEntities ctx = new tb01crmEntities())
            {


                List<HG_Prod_Catalog> hgc = (from c in ctx.HG_Prod_Catalog
                                       
                                        select c).ToList();
                HG_Prod_Catalog hgc1 = (from c in ctx.HG_Prod_Catalog
                                        where c.catalog_id==0
                                             select c).FirstOrDefault();
                InitTree(hgc1.Children, 0, hgc);
                return hgc1;
            }
        }
        public static void InitTree(List<HG_Prod_Catalog> Nds, long parentId, List<HG_Prod_Catalog> dt)
        {
            //dv = new DataView();
            HG_Prod_Catalog tmpNd;
            List<HG_Prod_Catalog> catalogtemp = dt.Where(c => c.catalog_father == parentId).ToList();
            foreach (HG_Prod_Catalog drv in catalogtemp)
            {
                tmpNd = new HG_Prod_Catalog();
                tmpNd = drv;    //节点ID 
                //tmpNd.Text = drv[2].ToString();     //节点名称 
                Nds.Add(tmpNd);
                //intId = drv[1].ToString();               //节点的父节点 
                InitTree(tmpNd.Children, tmpNd.catalog_id, dt);
            }
        }
        public void SaveNode(long fatherid,long id,string name)
        {
            try
            {
                using (tb01crmEntities ctx = new tb01crmEntities())
                {

                    if (id == 0)
                    {
                        HG_Prod_Catalog hgc = new HG_Prod_Catalog();
                        hgc.catalog_father = fatherid;
                        hgc.catalog_name = name;
                        ctx.AddToHG_Prod_Catalog(hgc);

                    }
                    else
                    {
                        HG_Prod_Catalog hgc = (from c in ctx.HG_Prod_Catalog
                                               where c.catalog_id == id
                                               select c).FirstOrDefault();
                        hgc.catalog_name = name;
                    }
                    ctx.SaveChanges();
                }
                RunInitTree();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
